package com.lute.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.Approver;
import com.lute.model.Employee;
import com.lute.model.User;
import com.lute.utils.ServerErrorResponse;

@Controller
public class AccountingPeriodCalendarEntriesUpdateServlet {
	
	@RequestMapping(value="/accountingPeriodUpdate", method= RequestMethod.POST, headers="Content-type=application/json") 
	public @ResponseBody String accountingPeriodCalendarEntriesUpdate(@RequestBody String jsonFromUI, HttpServletRequest request) throws JSONException {
		String result = "";
		JSONObject jsonReq;
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		try {
			jsonReq = new JSONObject(jsonFromUI);
		} catch(JSONException e) {
			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
			result = jsonRes.toString();
			return result;
		}
		
		String employeeIdTemp = jsonReq.getString("userId");
		String calendarEntriesToUpdate = jsonReq.getString("calendarEntries");
		String from = jsonReq.getString("from");
		
		int userId = Integer.parseInt(employeeIdTemp);
	    int sessionUserId = (Integer)session.getAttribute("sessionUserId");
	    String sessionRole = (String)session.getAttribute("role");
	    jsonRes.put("result", "");
	    
	    if (sessionRole.equals("admin")) {
	    	jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
	    	result = jsonRes.toString();
	    	return result;
	    }
	    
	    if (sessionRole.equals("clientAdmin")) {
	    	
	    	try {
	    		User user = User.getUserFromDB("id_user", userId);
//	    		JSONObject isAccountingPeriodStateChanged = new JSONObject();
//	    		System.out.print("CA -> ");
	    		
	    		if (user.getRole().getName().equals("admin") || user.getRole().getName().equals("clientAdmin")){
	    			// System.out.println("Calendar not updated");
	    			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
//	    			System.out.println("A | CA");
	    			result = jsonRes.toString();
	    			return result;
	    		} else {
	    			if (user.getRole().getName().equals("employee")){
	    				System.out.println(" Employee");
	    				jsonRes = Employee.verifyEmployeeEntriesAndChangeEmployeeAccountingPeriodState("id_user", userId, from, calendarEntriesToUpdate);
	    				if (jsonRes.get("result").equals("OK")){
	    					Employee.updateAccountingPeriodCalendarEntries("id_user", userId, from, calendarEntriesToUpdate);
	    				} else {
	    					result = jsonRes.toString();
	    					System.out.println(result);
	    					return result;
	    				}
	    				
	    			} else {
	    				System.out.println(" Approver");
	    				jsonRes = Approver.verifyEmployeeEntriesAndChangeEmployeeAccountingPeriodState("id_user", userId, from, calendarEntriesToUpdate);
	    				if (jsonRes.get("result").equals("OK")){
	    					Approver.updateAccountingPeriodCalendarEntries("id_user", userId, from, calendarEntriesToUpdate);
	    				} else {
	    					result = jsonRes.toString();
	    					System.out.println(result);
	    					return result;
	    				}
	    			}
	    			
	    			result = jsonRes.toString();
	    			if (!jsonRes.get("result").equals("OK")) {
	    				System.out.println("Result: AccountingPeriodState not updated");
	    				return result;
	    			} 
	    		}
	    	} catch (NullPointerException npe) {
	    		jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
	    		result = jsonRes.toString();
	    		npe.printStackTrace();
	    		return result;
	    	}
	    }
	    
	    if (sessionRole.equals("employee") || sessionRole.equals("approver")){
	    	boolean isAccountingPeriodCalendarEntriesUpdated = false;
	    	String state = null;
	    	try{
    		
	    		User user = User.getUserFromDB("id_user", userId);

		    	if (sessionUserId == userId){
		    		// update calendar
		    		try {
		    			if (sessionRole.equals("employee")){
		    				isAccountingPeriodCalendarEntriesUpdated = Employee.updateAccountingPeriodCalendarEntries("id_user", userId, from, calendarEntriesToUpdate);
		    			} else {
		    				isAccountingPeriodCalendarEntriesUpdated = Approver.updateAccountingPeriodCalendarEntries("id_user", userId, from, calendarEntriesToUpdate);
		    			}
		    		} catch(NullPointerException npe) {
		    			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
		    			result = jsonRes.toString();
		    			npe.printStackTrace();
		    			return result;
		    		}
		    		
		    		if (isAccountingPeriodCalendarEntriesUpdated == true) {
		    			// System.out.println("Calendar updated");
		    			if (sessionRole.equals("employee")){
		    				state = Employee.getEmployeeAccountingPeriodStateBasedOnEmployeeIdAndFrom("id_user", userId, from);
		    			} else {
		    				state = Approver.getApproverAccountingPeriodStateBasedOnApproverIdAndFrom("id_user", userId, from);
		    			}

		    			jsonRes.put("result", "OK");
	    				jsonRes.put("newEmployeeAccountingPeriodState", state);
		    			result = jsonRes.toString();
		    		} else {
		    			// System.out.println("Calendar not updated");
		    			jsonRes.put("result", ServerErrorResponse.MALFORMED_REQUEST.toString());
		    			result = jsonRes.toString();
		    			return result;
		    		}
		    	} else {
		    		jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
		    		result = jsonRes.toString();
		    		return result;
		    	}
	    	} catch (NullPointerException npe){
	    		jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
	    		result = jsonRes.toString();
	    		npe.printStackTrace();
	    		return result;
	    	}
	    	
	    }
//	    System.out.println("UserId from JSON: " + userId + "\nUserId from session: " + sessionUserId);
		return result;
	}

}
